var errorstr = new Array();
errorstr[11] = '格式不正确';
errorstr[12] = '月份超出范围';
errorstr[13] = '填入内容过多';
errorstr[14] = '应填入数字';
errorstr[15] = '数值过大';
errorstr[16] = '数值超出范围';
errorstr[17] = '请填入正数';
errorstr[18] = '请填入非负数';
errorstr[19] = '请填入整数';

function FieldValidator(){
  this.fields =new Array();                                   /*字段对象数组*/
  this.combFields = new Array();                               /*组合字段对象数组*/
  this.compareFields = new Array();                             /*比较字段对象数组*/
  this.alertstr = "";                                           /* 提示信息*/
}
/**
* 加入新的字段对象
* @fieldVO ： filed对象，附件VO
*/
FieldValidator.prototype.addField=function (fieldVO)
{
  if(fieldVO==null)
    return;

  var objCount=this.fields.length;               /*数组长度*/
  this.fields[objCount]=fieldVO;                 /*加对象到数组*/
}

/**
* 加入新的字段对象
* @fieldVO ： filed对象
*/
FieldValidator.prototype.addCombField=function (combFieldVO)
{
  if(combFieldVO==null)
    return;
  var objCount=this.combFields.length;               /*数组长度*/
  this.combFields[objCount]=combFieldVO;             /*加对象到数组*/
}


/**
* 加入新的字段对象
* @name ： 字段
*/
FieldValidator.prototype.addField=function (name,cnname,type,isnull,len1,len2,defaultval)
{
  var fVO = new fieldVO();
  fVO.setName(name);
  fVO.setCnName(cnname);
  fVO.setType(type);
  fVO.setIsNull(isnull);
  fVO.setMLen(len1);
  fVO.setLLen(len2);
  fVO.setDefaultValue(defaultval);
  
  //Bob add start by 2004/10/25
  //判断是否已经加验证,如果已加检验就返回
  
  for (var i=0;i<this.fields.length;i++)
  {
     if (this.fields[i].getName() == name)
      {
           return;
      }
  }
  //Bob add end by 2004/10/25
  var objCount=this.fields.length;               /*数组长度*/
  this.fields[objCount]=fVO;                 /*加对象到数组*/
}

/**
* 移出字段对象
* @name ： 字段
* Bob add start by 2004/10/25
*/
FieldValidator.prototype.removeField=function (name)
{

  //判断字段对象名是否相同
  var n = -1;
  for (var i=0;i<this.fields.length;i++)
  {
     if (this.fields[i].getName() == name)
      {
      	n = i;
           break;
      }
  }
  
  //移去第n个字段对象
  if (n>=0){
  	this.fields.splice(n,1);
  }
}

/**
* 加入组合字段对象
* @name ： 字段
*/
FieldValidator.prototype.addCombField=function (name,cnname,isnull,defaultval,checknum)
{
  var combfVO = new combFieldVO();
  combfVO.setName(name);
  combfVO.setCnName(cnname);
  combfVO.setIsNull(isnull);
  combfVO.setDefaultValue(defaultval);
  combfVO.setCheckNum(checknum);

  var objCount=this.combFields.length;               /*数组长度*/
  this.combFields[objCount]=combfVO;                 /*加对象到数组*/
}

/**
* 加入比较字段对象
* @name ： 字段
*/
FieldValidator.prototype.addCompareField=function (name,cnname,value,comparetype,defaultval)
{

  var comparefVO = new compareFieldVO();
  comparefVO.setName(name);
  comparefVO.setCnName(cnname);
  comparefVO.setValue(value);
  comparefVO.setCompareType(comparetype);
  comparefVO.setDefaultValue(defaultval);

  var objCount=this.compareFields.length;               /*数组长度*/
  this.compareFields[objCount]=comparefVO;                 /*加对象到数组*/
}
/**
* 重新设置比较字段对象
* @name ： 字段
*/
FieldValidator.prototype.setCompareField=function (name,cnname,value,comparetype,defaultval)
{
  for (var i=0;i<this.compareFields.length;i++)
  {
     if (this.compareFields[i].getName() == name)
      {
           this.compareFields[i].setName(name);
           this.compareFields[i].setCnName(cnname);
           this.compareFields[i].setValue(value);
           this.compareFields[i].setCompareType(comparetype);
           this.compareFields[i].setDefaultValue(defaultval);
           break;
      }

  }

}

/**
* 扩展检验事件
*/
FieldValidator.prototype.extendWork=function()
{
    return true;
}
/**
*  校验数据的合法性
*/
FieldValidator.prototype.checkValue = function(ckdoc)  //ckdoc应该是一个window对象
{
	//这里对fields中定义的变量进行检查
	var i;
	var iscorrect = true;
	var isitemcorrect = 1;
	var elvalue = null;
    var alertstr = "";
    //alert(this.fields.length);
	for(i=0;i<this.fields.length;i++)
	{

		isitemcorrect = true;
		this.fields[i].val = "";

		if(this.fields[i] != null && this.fields[i].getName() != null)
		{
			if(ckdoc.document.all(this.fields[i].getName()) == null)
				continue;
			elvalue =ckdoc.document.all(this.fields[i].getName()).value;

		}
		else
			continue;

		if(elvalue == null || this.Trim(elvalue) == "")
		{

			if(this.fields[i].getDefaultValue() != null && this.fields[i].getDefaultValue() != "")
				elvalue = ckdoc.document.all(this.fields[i].getName()).value = this.fields[i].getDefaultValue();
			if(this.fields[i].getIsNull())
				continue;
			else
			{
				alertstr += '请填入"' + this.fields[i].getCnName() + '"！\n';
				iscorrect = false;
                                 continue;
			}
		}

		switch(this.fields[i].getType())
		{
			case 'c'  :
						isitemcorrect = this.ischar(elvalue,this.fields[i].getMLen());
						break;
			case 'i'  :
						isitemcorrect = this.isint(elvalue,this.fields[i].getMLen());
                                               	if(isitemcorrect == 1)
							isitemcorrect =  compval(elvalue,this.fields[i]);
						break;
                        case 'pi'  :
						isitemcorrect = this.isplusint(elvalue,this.fields[i].getMLen());
                                               	if(isitemcorrect == 1)
							isitemcorrect =  compval(elvalue,this.fields[i]);
						break;
			case 'l'  :
						isitemcorrect =  this.islong(elvalue,this.fields[i].getMLen());
						if(isitemcorrect == 1)
							isitemcorrect =  compval(elvalue,this.fields[i]);
						break;
			case 'dl'  :
						isitemcorrect =  this.isdouble(elvalue,this.fields[i].getMLen(),this.fields[i].getLLen());
						if(isitemcorrect == 1)
							isitemcorrect =  compval(elvalue,this.fields[i]);
						break;
                        case 'pdl'  :
						isitemcorrect =  this.isplusdouble(elvalue,this.fields[i].getMLen(),this.fields[i].getLLen());
						if(isitemcorrect == 1)
							isitemcorrect =  compval(elvalue,this.fields[i]);
						break;
			case 'f'  :
						isitemcorrect =  this.isfloat(elvalue,this.fields[i].getMLen(),this.fields[i].getLLen());
						if(isitemcorrect == 1)
							isitemcorrect =  compval(elvalue,this.fields[i]);
						break;
			case 'd'  :
						isitemcorrect =  this.validatedate(elvalue);
						break;
			case 'dt'  :
						isitemcorrect =  this.validatedatetime(elvalue)
						break;
			case 'm'  :
						isitemcorrect =  this.ismail(elvalue,this.fields[i].getMLen());
						break;
			default	  :
						isitemcorrect = 0;
						break;
		}


		if(isitemcorrect != 1)
		{
			alertstr += "\""+ this.fields[i].getCnName() +'"项' + errorstr[isitemcorrect] + '！\n';
			iscorrect = false;
		}
		else
			this.fields[i].val = elvalue;
	}
       var combAlterStr = "";
        for( i=0;i<this.combFields.length;i++)
        {
            var  arrCombField = this.combFields[i].getName().split(";");
            var  arrCombFieldName = this.combFields[i].getCnName().split(";");
            var  tmpNum = 0;
            for(var j=0;j<arrCombField.length;j++)
            {
               if(arrCombField[j] != null )
		{
			if(ckdoc.document.all(arrCombField[j]) == null)
				continue;
			elvalue = ckdoc.document.all(arrCombField[j]).value;
                        if (elvalue !=null && this.Trim(elvalue) != '') {
                             tmpNum++;
                        }
                        else {
                             combAlterStr += '请填入"'+ arrCombFieldName[j] + '"！\n';
                        }
		}
		else
			continue;
            }

            if(this.combFields[i].getIsNull())
            {
                if (tmpNum!=0 && tmpNum < this.combFields[i].getCheckNum())
                {
                    alertstr +=  combAlterStr;
                    iscorrect = false;
                    continue;
                }
            }
            else
            {
                if (tmpNum < this.combFields[i].getCheckNum())
                {
                    alertstr += '请至少填入' + this.combFields[i].getCnName() + '！\n';
                    iscorrect = false;
                    continue;
                }
            }

        }

       for( i=0;i<this.compareFields.length;i++)
       {
              switch(this.compareFields[i].getCompareType())
              {
		  case '>'  :
                      if (this.compareFields[i].getValue() <= this.compareFields[i].getDefaultValue())
                      {
                         alertstr +=  this.compareFields[i].getCnName() + '！\n';
                         iscorrect = false;
                       }
                       break;
                   case '<'  :
                      if (this.compareFields[i].getValue() >= this.compareFields[i].getDefaultValue())
                      {
                         alertstr +=  this.compareFields[i].getCnName() + '！\n';
                         iscorrect = false;
                       }
                       break;
                    case '>='  :
                         if (this.compareFields[i].getValue() < this.compareFields[i].getDefaultValue())
                         {
                            alertstr +=  this.compareFields[i].getCnName() + '！\n';
                            iscorrect = false;
                         }
                         break;
                     case '<='  :
                         if (this.compareFields[i].getValue() > this.compareFields[i].getDefaultValue())
                         {
                            alertstr +=  this.compareFields[i].getCnName() + '！\n';
                            iscorrect = false;
                          }
                          break;
                      case '='  :
                          if (this.compareFields[i].getValue() != this.compareFields[i].getDefaultValue())
                          {
                              alertstr +=  this.compareFields[i].getCnName() + '！\n';
                              iscorrect = false;
                           }
                           break;
                      default	  :
			       break;
            }

        }

        this.alertstr = alertstr;
        clientflag=this.extendWork();
	if(!iscorrect | !clientflag)
	    alert( this.alertstr);
	return   clientflag & iscorrect;
}

/**
* 校验是否是正确的日期
*/

FieldValidator.prototype.validatedate =function( strValue )
{
  /*
  strValue must be as:  yyyy/mm/dd or yyyy-mm-dd or yyyy.mm.dd
  */
  var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}(\-|\/|\.)\d{1,2}$/;
  if(!objRegExp.test(strValue))
  {
    return 11;
  }
  else{
    var strSeparator = strValue.substring(4,5);
    var arrayDate = strValue.split(strSeparator); //split date into month, day, year
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31};
    var intDay = eval(arrayDate[2]);
    var intMonth = eval(arrayDate[1]);
    if(intMonth > 12 || intMonth <= 0) return 12;
    if(arrayDate[1].length < 2) arrayDate[1] = '0' + arrayDate[1];

    //check if month value and day value agree
    if(arrayLookup[arrayDate[1]] != null ) {
      if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
        return 1; //found in lookup table, good date
    }
    //check for February
    if(intMonth == 2)
    {
      var intYear = parseInt(arrayDate[0]);
      if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
        return 1;
    }

  }
  return 11;
}
/**
* 校验是否是正确的时间
*/
FieldValidator.prototype.validatetime = function( strValue )
{
  /*
  strValue must be as:  hh:mm:ss or hh:mm;
  */
  var arrayTime = strValue.split(":")
  if (arrayTime.length==2)
  {
  	  strHour=arrayTime[0];
	  strMinute=arrayTime[1];

	  if((parseInt(strHour)>=0 && parseInt(strHour)<=24) && (parseInt(strMinute)>=0 && parseInt(strMinute)<=60) )
	  	return 1;
  }
  if (arrayTime.length==3)
  {
  	  strHour=arrayTime[0];
	  strMinute=arrayTime[1];
	  strSecond=arrayTime[2];
	  if((parseInt(strHour)>=0 && parseInt(strHour)<=24) && (parseInt(strMinute)>=0 && parseInt(strMinute)<=60) && (parseInt(strSecond)>=0 && parseInt(strSecond)<=60))
	  	return 1;
	  return 11;
  }
  return 11;
}
/**
* 校验是否是正确的日期时间
*/
FieldValidator.prototype.validatedatetime =function( strValue )
{
	arrayValue = strValue.split(" ");
	if(arrayValue.length==2)
	{
		var rv = this.validatedate(arrayValue[0]);
		if(rv == 1)
			rv = this.validatetime(arrayValue[1]);
		return rv;
	}
	return 11;
}
/**
* 校验是否是字符，并检查长度是否越界
*/
FieldValidator.prototype.ischar =function(val,len)
{
	if(getUniCodeLength(val)<=len)
            return 1;
	return 13;
}
/**
* 校验是否是整型，并检查长度是否越界
*/
FieldValidator.prototype.isint =function(val,len)
{

        if (this.Trim(val) == '') return 14;
	if(isNaN(val)) return 14;
        if(val.indexOf(".")>0) return 19;
	if(val.length<=len) return 1;
	return 15;
}

/**
* 校验是否是正数，并检查长度是否越界
*/
FieldValidator.prototype.isplusint =function(val,len)
{

        if (this.Trim(val) == '') return 14;
	if(isNaN(val)) return 14;
        if(val.indexOf(".")>0) return 19;
        if (val <=0) return 17;
	if(val.length<=len) return 1;
	return 15;
}
/**
* 校验是否是长整型，并检查长度是否越界限
*/
FieldValidator.prototype.islong = function(val,len)
{
	//与isint一致
	return isint(val,len);
}
FieldValidator.prototype.isdouble = function(val,len1,len2)
{
        if (this.Trim(val) == '') return 14;
	if(isNaN(val)) return 14;
	if(val.indexOf(".")<0)
	{
		if(val.length<=len1) return 1;
		return 15;
	}
	if(val.substring(0,val.indexOf(".")).length <= len1 && val.length-val.indexOf('.')-1 <= len2)
		return 1;
	return 16;
}

FieldValidator.prototype.isplusdouble = function(val,len1,len2)
{
        if (this.Trim(val) == '') return 14;
	if(isNaN(val)) return 14;
        if (val <=0) return 17;
	if(val.indexOf(".")<0)
	{
		if(val.length<=len1) return 1;
		return 15;
	}
	if(val.substring(0,val.indexOf(".")).length <= len1 && val.length-val.indexOf('.')-1 <= len2)
		return 1;
	return 16;
}

/**
* 校验是否是浮点类型，并检查长度是否越界限
*/
FieldValidator.prototype.isfloat =function(val,len1,len2)
{
	//与isfloat一致
	return isdouble(val,len1,len2);
}

/**
* 校验是否是正确的电邮
*/
FieldValidator.prototype.ismail = function(val,len)
{
	var i=0 ;
	var slength=val.length;
	if (val.length>len)
		return 13;
	if(val.charAt(0)=="@")
		return 11;
	while((i<slength)&&(val.charAt(i)!="@"))
		i++;
	if (i>=slength)
		return 11;
	else i+=2;
	while((i<slength)&&(val.charAt(i)!="."))
		i++;
	if(i>=slength-1)
		return 11;
	return 1;
}


////////////////////////////////////////////////////////////////////////////////

//以下是调用函数
////////////////////////////////////////////////////////////////////////////////
//验证EMAIL
function checkmail(mail)
{
    var  strr;
    re=/(\w+@\w+\.\w+)(\.{0,1}\w*)(\.{0,1}\w*)/i;
    re.exec(mail);
    if  (RegExp.$3!=""&&RegExp.$3!="."&&RegExp.$2!=".")  strr=RegExp.$1+RegExp.$2+RegExp.$3
    else
        if  (RegExp.$2!=""&&RegExp.$2!=".")  strr=RegExp.$1+RegExp.$2
        else    strr=RegExp.$1
    if  (strr!=mail)  {alert("请填写正确的邮件地址！");return false}
    return  true;
}

function compval(val1,val2)
{
	if(val2 == null || val2 == '')
		return 1;
	var val11 = parseFloat(val1);
	if(val2.maxval != null && val2.maxval != '')
		if(val11 - val2.maxval > 0.00001)
			return 16;
	if(val2.minval != null && val2.minval != '')
		if(val11 - val2.minval < -0.00001)
			return 16;
	return 1;
}
function compareval(val1,val2,msg)
{
	var temp1 = '';
	var temp2 = '';

	if (document.all(val1) !=null)
		temp1 = document.all(val1).value;
	if (document.all(val2) !=null)
		temp2 = document.all(val2).value;

	if(temp1 == null || temp1 == '' || temp2 == null || temp2 == '')
		return true;

	var retval = (parseFloat(temp2) > parseFloat(temp1));

	if (!retval && msg != null && msg != '')
		alert(msg);

	return retval;
}


var regexpcn = /(%u[A-F0-9]{4})/gi;
var regexp = /(%[A-F0-9]{2})/gi;
var regval = null;
function getUniCodeLength(unicodeval)
{
	if(unicodeval == null) return 0;
	regval = escape(unicodeval);
	regval = regval.replace(regexpcn,"aa");
	regval = regval.replace(regexp,"a");
	return regval.length;
}

/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function LTrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" 　\t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var j=0, i = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" 　\t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;


      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
FieldValidator.prototype.Trim = function(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return RTrim(LTrim(str));
}


/*--------------------------------------------------------------------------------
  compareFieldVO
   比较字段对象

---------------------------------------------------------------------------------*/
function compareFieldVO()
{
  this.name = "";            //字段名
  this.value="";              //字段值
  this.cnname="";            //中文名
  this.compareType="";         //比较方式
  this.defaultval="";         //缺省值
 }

compareFieldVO.prototype.setName=function (name)
{
  this.name=name;
}
compareFieldVO.prototype.getName=function ()
{
  return this.name;
}
compareFieldVO.prototype.setValue=function (value)
{
  this.value=value;
}

compareFieldVO.prototype.getValue=function ()
{
  return this.value;
}

compareFieldVO.prototype.setCnName=function (cnname)
{
  this.cnname=cnname;
}

compareFieldVO.prototype.getCnName=function ()
{
  return this.cnname;
}

compareFieldVO.prototype.setCompareType=function (compareType)
{
  this.compareType=compareType;
}

compareFieldVO.prototype.getCompareType=function ()
{
  return this.compareType;
}

compareFieldVO.prototype.setDefaultValue=function (defaultval)
{
  this.defaultval=defaultval;
}

compareFieldVO.prototype.getDefaultValue=function ()
{
  return this.defaultval;
}


/*--------------------------------------------------------------------------------
  combFieldVO
   组合字段对象

---------------------------------------------------------------------------------*/
function combFieldVO()
{
  this.name="";              //字段名
  this.cnname="";            //中文名
  this.isnull="";            //能否为空
  this.defaultval="";         //缺省值
  this.checkNum =0;          //检测数量
  this.isCompare =false;     //是否需要值比较；
}

combFieldVO.prototype.setName=function (name)
{
  this.name=name;
}

combFieldVO.prototype.getName=function ()
{
  return this.name;
}

combFieldVO.prototype.setCnName=function (cnname)
{
  this.cnname=cnname;
}

combFieldVO.prototype.getCnName=function ()
{
  return this.cnname;
}

combFieldVO.prototype.setIsNull=function (isnull)
{
  this.isnull=isnull;
}

combFieldVO.prototype.getIsNull=function ()
{
  return this.isnull;
}

combFieldVO.prototype.setDefaultValue=function (defaultval)
{
  this.defaultval=defaultval;
}

combFieldVO.prototype.getDefaultValue=function ()
{
  return this.defaultval;
}

combFieldVO.prototype.setCheckNum=function (checkNum)
{
  this.checkNum=checkNum;
}

combFieldVO.prototype.getCheckNum=function ()
{
  return this.checkNum;
}

combFieldVO.prototype.setIsCompare=function (isCompare)
{
  this.isCompare=isCompare;
}

combFieldVO.prototype.getIsCompare=function ()
{
  return this.isCompare;
}

/*--------------------------------------------------------------------------------
fieldVO
 字段对象

---------------------------------------------------------------------------------*/

function fieldVO()
{
  this.name="";              //字段名
  this.cnname="";            //中文名
  this.isnull="";            //能否为空
  this.type="";              //字段类型
  this.len1=0;               //长度
  this.len2="";               //精度
  this.defaultval="";         //缺省值
}

fieldVO.prototype.setName=function (name)
{

  this.name=name;
}

fieldVO.prototype.getName=function ()
{
  return this.name;
}

fieldVO.prototype.setCnName=function (cnname)
{

  this.cnname=cnname;
}

fieldVO.prototype.getCnName=function ()
{
  return this.cnname;
}


fieldVO.prototype.setIsNull=function (isnull)
{

  this.isnull=isnull;
}

fieldVO.prototype.getIsNull=function ()
{
  return this.isnull;
}


fieldVO.prototype.setType=function (type)
{

  this.type=type;
}

fieldVO.prototype.getType=function ()
{
  return this.type;
}

fieldVO.prototype.setMLen=function (len1)
{

  this.len1=len1;
}

fieldVO.prototype.getMLen=function ()
{
  return this.len1;
}

fieldVO.prototype.setLLen=function (len2)
{

  this.len2=len2;
}

fieldVO.prototype.getLLen=function ()
{
  return this.len2;
}


fieldVO.prototype.setDefaultValue=function (defaultval)
{
  this.defaultval=defaultval;
}

fieldVO.prototype.getDefaultValue=function ()
{
  return this.defaultval;
}